define([
  'EventBus'
], function (EventBus) {
  'use strict';
  $.form.utils.modalFn = function (url, data, title, callback, loading, tips, cancelCallback, endCallback, options) {
    data = data || {};
    options = options || {};
    function successFn(res) {
      if (typeof (res) === 'object') {
        return $.msg.auto(res);
      }
      var area = data.area || [];

      if (_.isArray(area)) {
        area.push(data.ww || '700px');
        area.push(data.hh || ($(window).height() * 0.8) + 'px');
      }

      var offset = [data.top || options.top || '2%'];
      if (data.left || options.top) {
        offset.push(data.left || options.top)
      }
      var userOpt = {
        offset: data.offset || offset,
        content: res,
        title: title || ''
      };
      layer.open($.extend({
        type: 1,
        btn: false,
        anim: 2,
        area: area,
        offset: data.offset || offset,
        content: res,
        zIndex: 200,
        // maxmin: true,
        // shade: 0,
        shadeClose: false,
        title: title || '',
        success: function (dom, index) {
          // 聚焦元素失焦 避免再次按enter键触发不必要事件
          document.activeElement.blur();
          // 此窗口完成时需要自动关闭
          $.msg.addAutoSuccessCloseIndex(index);
          var $container = $(dom);
          /* 处理样式及返回按钮事件 */
          $container.find('[data-close]').off('click').on('click', function () {
            if ($(this).attr('data-confirm')) {
              $.msg.confirm($(this).attr('data-confirm'), function () {
                layer.close(index);
              });
            } else {
              layer.close(index);
            }
          });
          /* 事件重载 */
          $.form.reInit($container);
        },
        cancel: function () {
          if (typeof cancelCallback === 'function') {
            cancelCallback.call(this);
          }
        },
        end: function () {
          if (typeof endCallback === 'function') {
            endCallback.call(this);
          }
        }
      }, options, userOpt));
      return (typeof callback === 'function') && callback.call(this);
    }
    function defaultloader() {
      $.el.get({
        url: ELMP.getUrl(url),
        data: data,
        dataType: 'html',
        success: function (res) {
          successFn(res, true);
        }
      });
    }
    var prevent = false;
    var preventDefault = function () {
      prevent = true;
    };
    if (EventBus.has('core:form:section:custom:load')) {
      EventBus.emit('core:form:section:custom:load', {
        params: {
          url: url,
          data: data,
          callback: callback,
          loading: loading,
          tips
        },
        // 成功回调
        successFn: successFn,
        // 默认的加载逻辑
        defaultloader: defaultloader,
        // 阻止默认加载逻辑
        preventDefault: preventDefault
      });
    }
    if (!prevent) {
      defaultloader();
    }
  }
});